# @Time : 2025-02-14 14:34
# @Author : Fioman 
# @Phone : 13149920693
import cv2
import numpy as np


def resize_image(image, max_width):
    """调整图像大小以适应最大宽度"""
    height, width = image.shape[:2]
    if width > max_width:
        new_height = int(max_width * height / width)
        image = cv2.resize(image, (max_width, new_height))
    return image


def concatenate_images(image1, image2):
    """拼接两个图像"""
    # 调整图像大小
    max_width = 980  # 设定最大宽度
    image1 = resize_image(image1, max_width)
    image2 = resize_image(image2, max_width)

    # 垂直拼接
    concatenated_image = np.vstack((image1, image2))
    return concatenated_image


def compress_image(image, max_size_kb):
    """压缩图像以确保大小不超过指定的KB"""
    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
    success, encoded_image = cv2.imencode('.jpg', image, encode_param)
    while success and len(encoded_image) > max_size_kb * 1024:
        encode_param[1] -= 1  # 减少质量
        success, encoded_image = cv2.imencode('.jpg', image, encode_param)
    return encoded_image


if __name__ == '__main__':
    # 读取图像
    image1 = cv2.imread(r'F:\raw_2025\pic\6.png')
    image2 = cv2.imread(r'F:\raw_2025\pic\5.jpg')

    # 拼接图像
    concatenated_image = concatenate_images(image1, image2)

    # 压缩图像
    compressed_image = compress_image(concatenated_image, 500)

    # 解码图像为NumPy数组
    decoded_image = cv2.imdecode(np.frombuffer(compressed_image, np.uint8), cv2.IMREAD_COLOR)

    # 保存图像
    cv2.imwrite('imageRes01.jpg', decoded_image)
